
import 'package:e_reception_flutter/common_widgets/common_confirm_cancel_dialog/common_confirm_cancel_dialog.dart';
import 'package:e_reception_flutter/common_widgets/common_fixed_height_confirm_button_widget/common_fixed_height_confirm_button_widget.dart';
import 'package:e_reception_flutter/singleton/theme_repository/theme_repository.dart';
import 'package:e_reception_flutter/utils/router_utils.dart';
import 'package:e_reception_flutter/utils/screen_utils.dart';
import 'package:e_reception_flutter/utils/vg_toast_utils.dart';
import 'package:e_reception_flutter/utils/vg_tool_utils.dart';
import 'package:e_reception_flutter/vg_widgets/vg_top_bar_widget/vg_top_bar_widget.dart';
import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:vg_base/vg_arch_lib.dart';
import 'package:vg_base/vg_string_util_lib.dart';
import 'binding_terminal/widgets/binding_terminal_auto_switch_dialog.dart';

///设置定时开关机页面
class SetEachDayOnOffPage extends StatefulWidget{
  ///路由名称
  static const String ROUTER = "SetEachDayOnOffPage";
  final DateTime startDateTime;
  final DateTime endDateTime;
  final String day;
  final Function(String status, String time) onSet;
  final int activeCount;

  const SetEachDayOnOffPage({
    Key key,
    this.startDateTime,
    this.endDateTime,
    this.day,
    this.onSet,
    this.activeCount,
  }) : super(key: key);

  @override
  _SetEachDayOnOffPageState createState() => _SetEachDayOnOffPageState();

  ///跳转方法
  ///返回Map
  static Future<Map<String,dynamic>> navigatorPush(
      BuildContext context, DateTime startDateTime,
      DateTime endDateTime, String day, Function onSet, int activeCount) {
    return RouterUtils.routeForFutureResult(
      context,
      SetEachDayOnOffPage(
        startDateTime:startDateTime,
        endDateTime:endDateTime,
        day:day,
        onSet:onSet,
        activeCount:activeCount,
      ),
      routeName: SetEachDayOnOffPage.ROUTER,
    );
  }
}

class _SetEachDayOnOffPageState extends BaseState<SetEachDayOnOffPage>{

  DateTime _startDateTime;
  DateTime _endDateTime;
  String _day;
  bool _isAlive;
  String _originTime;
  @override
  void initState() {
    super.initState();
    final DateTime nowDateTime = DateTime.now();
    _startDateTime = widget?.startDateTime ??
        DateTime(nowDateTime.year, nowDateTime.month, nowDateTime.day,
            DEFAULT_START_HOUR);
    _endDateTime = widget?.endDateTime ??
        DateTime(nowDateTime.year, nowDateTime.month, nowDateTime.day,
            DEFAULT_END_HOUR);
    _originTime = getAutoOffTimeStr();
    _day = widget?.day;
    _isAlive = false;
  }




  @override
  Widget build(BuildContext context) {
    return Scaffold(
      resizeToAvoidBottomPadding: false,
      resizeToAvoidBottomInset: false,
      backgroundColor: ThemeRepository.getInstance().getBgOrSplitColor_191E31(),
      body: _toMainWidget(),
    );
  }

  @override
  void dispose() {
    super.dispose();
  }

  _judgeAlive(){
    String time = getAutoOffTimeStr();
    setState(() {
      _isAlive = (time != _originTime);
    });
  }

  Widget _toMainWidget(){
    return Column(
      children: [
        _toTopBarWidget(),
        _toTimeWidget(),
        SizedBox(height: 30,),
        _toConfirmWidget(),
        SizedBox(height: 16,),
        _toCancelWidget(),
      ],
    );
  }

  Widget _toTopBarWidget() {
    return VgTopBarWidget(
      title: _day??"",
      backgroundColor: ThemeRepository.getInstance().getBgOrSplitColor_191E31(),
      isShowBack: true,
    );
  }

  Widget _toTimeWidget(){
    return Container(
      color: ThemeRepository.getInstance().getCardBgColor_21263C(),
      height: 188,
      child: _toTimeChooseWidget(),
    );
  }

  ///时间选择
  Widget _toTimeChooseWidget() {
    return CupertinoTheme(
      data: CupertinoThemeData(
          textTheme: CupertinoTextThemeData(
              dateTimePickerTextStyle: TextStyle(color: Colors.white))),
      child: Row(
        children: <Widget>[
          Expanded(
            child: CupertinoDatePicker(
              mode: CupertinoDatePickerMode.time,
              use24hFormat: true,
              initialDateTime: _startDateTime,
              onDateTimeChanged: (DateTime newStartDateTime) {
                _startDateTime = newStartDateTime;
                _judgeAlive();
              },
            ),
          ),
          Text(
            "至",
            maxLines: 1,
            overflow: TextOverflow.ellipsis,
            style: TextStyle(color: Colors.white, fontSize: 18, height: 1.2),
          ),
          Expanded(
            child: CupertinoDatePicker(
              mode: CupertinoDatePickerMode.time,
              use24hFormat: true,
              initialDateTime: _endDateTime,
              onDateTimeChanged: (DateTime newEndDateTime) {
                _endDateTime = newEndDateTime;
                _judgeAlive();
              },
            ),
          ),
        ],
      ),
    );
  }

  _toConfirmWidget() {
    return CommonFixedHeightConfirmButtonWidget(
      onTap: (){
        // if(!_isAlive){
        //   return;
        // }
        if((_endDateTime?.millisecondsSinceEpoch??0) <= (_startDateTime?.millisecondsSinceEpoch??0)){
          VgToastUtils.toast(context, "结束时间不能早于开始时间");
          return;
        }
        RouterUtils.pop(context);
        widget?.onSet?.call("01", getAutoOffTimeStr());
      },
      // isAlive: _isAlive??false,
      isAlive: true,
      height: 40,
      margin: EdgeInsets.symmetric(horizontal: 15),
      padding: EdgeInsets.symmetric(horizontal: 15),
      selectedBgColor:
      ThemeRepository.getInstance().getPrimaryColor_1890FF(),
      unSelectBgColor:
      ThemeRepository.getInstance().getLineColor_3A3F50(),
      selectedTextStyle: TextStyle(
        color: Colors.white, fontSize: 15,),
      unSelectTextStyle: TextStyle(
        color: ThemeRepository.getInstance().getHintGreenColor_5E687C(), fontSize: 15,),
      text: "保存",
      textSize: 15,
    );

  }

  _toCancelWidget() {
    return GestureDetector(
      behavior: HitTestBehavior.opaque,
      onTap: ()async{
        if((widget?.activeCount??0) <= 1){
          bool result =
              await CommonConfirmCancelDialog.navigatorPushDialog(context,
            title: "提示",
            content: "确定关闭定时开关机功能？",
            cancelText: "取消",
            confirmText: "关闭",
            confirmBgColor: ThemeRepository.getInstance()
                .getMinorRedColor_F95355(),);
          if (result ?? false) {
            RouterUtils.pop(context);
            //代表直接关闭
            widget?.onSet?.call("11", "");
          }
          return;
        }
        RouterUtils.pop(context);
        widget?.onSet?.call("00", getAutoOffTimeStr());
      },
      child: Container(
        alignment: Alignment.center,
        margin: EdgeInsets.symmetric(horizontal: 15),
        padding: EdgeInsets.symmetric(horizontal: 15),
        height: 40,
        decoration: BoxDecoration(
          borderRadius: BorderRadius.all(Radius.circular(20)),
          color: ThemeRepository.getInstance().getBgOrSplitColor_191E31(),
          border: Border.all(
              color: Color(0xFF3A3F50),
              width: 1),
        ),
        child: Text(
            "不自动开机",
            style: TextStyle(
              color: ThemeRepository.getInstance().getTextColor_D0E0F7(),
              fontSize: 15,
            )
        ),
      ),
    );
    return CommonFixedHeightConfirmButtonWidget(
      onTap: (){
        RouterUtils.pop(context);
        widget?.onSet?.call("00", getAutoOffTimeStr());
      },
      isAlive: true,
      height: 40,
      padding: EdgeInsets.symmetric(horizontal: 15),
      selectedBoxBorder: Border.all(
          color: ThemeRepository.getInstance()
              .getLineColor_3A3F50(),
          width: 1),
      selectedBgColor:
      ThemeRepository.getInstance().getBgOrSplitColor_191E31(),
      unSelectBgColor:
      ThemeRepository.getInstance().getBgOrSplitColor_191E31(),
      selectedTextStyle: TextStyle(
        color: ThemeRepository.getInstance().getTextColor_D0E0F7(), fontSize: 15,),
      text: "不自动开机",
      textSize: 15,
    );

  }
  String getAutoOffTimeStr(){
    if(_startDateTime == null || _endDateTime == null){
      return null;
    }
    return "${VgToolUtils.twoDigits(_startDateTime.hour)}:${VgToolUtils.twoDigits(_startDateTime.minute)}"
        "-"
        "${VgToolUtils.twoDigits(_endDateTime.hour)}:${VgToolUtils.twoDigits(_endDateTime.minute)}";
  }
}

